/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  This product includes software developed by the
 *  Apache Software Foundation (http://www.apache.org/).
 *  The Apache Software Foundation in no way endorses or
 *  promotes this product.
 */
package com.codemagi.taglibs.input;

import com.codemagi.util.*;
import java.text.DateFormat;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.*;

/**
 *  This class implements the &lt;input:calendar&gt; tag, which presents a
 *  &lt;text&gt; form element with additional code to implement the 
 *  JSCalendar date picker developed by Mihai Bazon
 *
 *  @version 1.0
 *  @author Shawn Bayern for Apache Software Foundation (Original Author)
 *  @author August Detlefsen for CodeMagi, Inc.
 *  @author Mihai Bazon for jscalendar 
 *  @see http://sourceforge.net/projects/jscalendar
 */
public class Calendar extends Input {

    private Boolean hideStylesheet   = new Boolean(false);
    private Boolean hideJavascript   = new Boolean(false);
    private Date defaultDate;           // default date
    private String defaultDateString = null;   // formatted date string
    private static DateFormat dateFormat = DateUtils.CALENDAR_FORMAT;

    public void setHideStylesheet(Boolean newValue) {
	if (newValue != null) hideStylesheet = newValue;
    }

    public void setHideJavascript(Boolean newValue) {
	if (newValue != null) hideJavascript = newValue;
    }

    public void setDefault(Date x) {
	log.debug("DateSelect.setDefault() Date to: " + x);
	defaultDate = x;
	defaultDateString = DateUtils.formatDate(defaultDate, dateFormat);
    }

    public static DateFormat getDateFormat() {
	return dateFormat;
    }

    public String getFormattedDefaultDate() {
	return defaultDateString;
    }

    public int doStartTag() throws JspException {
	try {
            // sanity check
            if (name == null || name.equals("")) {
                throw new JspTagException("invalid null or empty 'name'");
	    }
	    
	    // get what we need from the page
	    ServletRequest req = pageContext.getRequest();
	    JspWriter out = pageContext.getOut();
	    
	    // start building up the tag
	    out.println();
	    out.println("<TABLE BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"0\" CLASS=\"cminput_calendar\"><TR><TD VALIGN=\"middle\">");
	    out.println("<input type=\"text\"");
	    out.println("    name=\"" + Util.quote(name) + "\"");
	    out.println("    id=\"" + Util.quote(name) + "\"");

	    //disable the form field if disabled is set
	    if (disabled) {
		out.println("    readonly=\"readonly\"");
		out.println("    OnFocus=\"blur();\"");
		appendAttribute("style", "cursor:default;");
	    }

	    /*
	     * print out the value from the request if it's there, or
	     * use the default value if it's not
	     */
	    String param = getParameter(name, (HttpServletRequest)req);

	    if ( override ) {
		out.println("    value=\"" + Util.quote(getFormattedDefaultDate()) + "\"");
	    } else if (param != null ) {
		out.print( "    value=\"" + Util.quote(param) + "\"");
	    } else if ( getFormattedDefaultDate() != null ) {
		out.print("    value=\"" + Util.quote(getFormattedDefaultDate()) + "\"");
	    }
	    
	    // include any attributes we've got here
	    Util.printAttributes(out, attributes);
	    
	    //if this is a required field and it is not filled out, do something...
	    if ( !Utils.isEmpty((String)req.getAttribute("error_" + name + "_error")) ) {
                out.println("    class=\"cminput_error\"");
            }

	    // end the text tag
	    out.println("/>");
	    out.println("</TD><TD VALIGN=\"middle\">");

	    out.println("<img id=\"" + Util.quote(name) + "_trigger\" src=\"/js/cal/button.gif\" />");
	    
	    out.println("</TD></TR></TABLE>");

	    if (!"true".equals(pageContext.getAttribute("calendarImported"))) {

		// add reference to calendar javascript code
		if (!hideStylesheet) {
		    out.println("<style type=\"text/css\">");
		    out.println("   @import url(/js/cal/calendar.css);");
		    out.println("</style>");
		}

		if (!hideJavascript) {
		    out.println("<script type=\"text/javascript\"");
		    out.println("   src=\"/js/cal/calendar.js\">");
		    out.println("</script>");
		    out.println("<script type=\"text/javascript\"");
		    out.println("   src=\"/js/cal/lang/calendar-en.js\">");
		    out.println("</script>");
		    out.println("<script type=\"text/javascript\"");
		    out.println("   src=\"/js/cal/calendar-setup.js\">");
		    out.println("</script>");

		    //flag that the reference code has been added
		    pageContext.setAttribute("calendarImported","true");
		}
	    }

	    //add code for new calendar object
	    if (!disabled && !hideJavascript) {
		out.println("<script type=\"text/javascript\">");
		out.println("   Calendar.setup( { ");
		out.println("   inputField  : \"" + Util.quote(name) + "\",");
		out.println("   ifFormat  : \"%m/%d/%Y\",");
		out.println("   button      : \"" + Util.quote(name) + "_trigger\"");
		out.println("   } );");
		out.println("</script>");
	    }

	    //show the error message
	    if (showError) { 
		String errorMessage = (String)req.getAttribute(name + "_error_message");
		if (errorMessage != null && !"".equals(errorMessage) ) { 
		    out.print( "<BR><SPAN CLASS=\"input_error_msg\">" + errorMessage + "</SPAN>");
		}
	    }

    
	} catch (Exception ex) {
	    throw new JspTagException(ex.getMessage());
	}
	return SKIP_BODY;
    }
}

